package com.toolkit.interceptor;

import com.alibaba.fastjson2.JSON;
import com.toolkit.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {
    //controller层之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        String uri= request.getRequestURI();
        String xmlJson = JSON.toJSONString(request.getParameterMap());
        String body = null;
        if(request.getInputStream().available() != 0){
            body = new String(StreamUtils.copyToByteArray(request.getInputStream()));
        }
        String ipString = IpUtil.getIpAddr(request);
        Map<String,String> map=new HashMap<>();
        map.put("ip",ipString);
        map.put("uri",uri);
        map.put("formParam",xmlJson);
        map.put("postParam",body);
        map.put("token",token);
        log.info(JSON.toJSONString(map));
        return true;
    }
}
